from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import *
from pathlib import Path
import os
import sys


def resource_path(relative_path):
    """获取打包后资源的绝对路径"""
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


class AudioSource:
    def __init__(self):
        super().__init__()
        audio_path = Path(resource_path('res/audio'))
        audio_names = ['button', 'finish', 'saved']

        self.audio_dict = {}
        for name in audio_names:
            player = QMediaPlayer()
            url = QUrl.fromLocalFile(str(audio_path / (name + '.mp3')))
            content = QMediaContent(url)
            player.setMedia(content)
            self.audio_dict[name] = player

    def play_audio(self, name, volume=1):
        """通过音频文件的名称进行播放"""
        audio = self.audio_dict.get(name)

        if not audio:
            QMessageBox.critical(self, '错误', '没有这个音频文件！')
            return

        audio.setVolume(volume)
        audio.play()
